import Vue from "vue";
import VueRouter from "vue-router";


Vue.use(VueRouter);

// 解决重复访问路由报错
// 原理大概就是捕获错误吧
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(path) {
	originalPush.call(this, path).catch(err => err);
}

const routes = [
	{
		path: "/",
		redirect: "/home"
	},
	{
		path: "/home",
		component: () => import('@/views/home/index'),
		meta: { title: "首页" }
	},
	{
		path: "/login",
		component: () => import('@/views/login/index'),
		meta: { title: "登录" }
	},
	{
		path: '/404',
		component: () => import('@/views/404'),
		meta: { title: "找不到页面" },
	},
	{
		path: "/profile",
		name: "profile",
		redirect: "/profile/userInfo",
		component: () => import('@/views/profile/index'),
		meta: { title: "个人中心" },
		children: [
			{
				path: "userInfo",
				name: "userInfo",
				component: () => import('@/views/profile/userInfo')
			}, {
				path: "editor",
				name: "editor",
				component: () => import('@/views/profile/editor')
			}, {
				path: "articleList",
				name: "articleList",
				component: () => import('@/views/profile/articleList')
			}, {
				path: "blogSetting",
				name: "blogSetting",
				component: () => import('@/views/profile/blogSetting')
			}
		]
	},
	{
		path: "/articles/:author/:articleId",
		component: () => import('@/views/article/index')
	},
	{
		path: "/articles/:author",
		component: () => import('@/views/article/index')
	},
	{
		path: "/question",
		name: "question",
		component: () => import('@/views/question/index'),
		meta: { title: "有问必答" }
	},
	{
		path: "/class",
		name: "class",
		component: () => import('@/views/class/index'),
		meta: { title: "班级" }
	},

];

// 创建路由
export const createRouter = () => new VueRouter({
	mode: "history",
	base: process.env.BASE_URL,
	// 页面返回时回到顶部 
	// https://router.vuejs.org/zh/guide/advanced/scroll-behavior.html
	scrollBehavior: () => ({ y: 0 }),
	routes: routes
});

const router = createRouter();

// 重置路由（退出登录后）
export function resetRouter() {
	const newRouter = createRouter();
	router.matcher = newRouter.matcher;
}

export default router;
